<script lang="ts" setup>
import { storeToRefs } from 'pinia'
import { getDetailWallApi, getDownloadWallApi, getSetupScoreApi, getUserWallListApi, getWallListApi } from '@/api/index'
import { useWallStore } from '@/store'
import { capsuleButtonHeight, safeAreaInsets } from '@/utils/systemInfo'
import {
  getCurrentDate,
  getCurrentTime,
  goHome,
} from '@/utils/utils'

definePage({
  style: {
    navigationBarTitleText: '预览',
    navigationStyle: 'custom',
  },
})
type IPopupType = { open: () => void, close: () => void } | null
interface IWallData { [key: string]: any }
let { classificationName, classList } = storeToRefs(useWallStore())
let wallData = reactive<IWallData>({})
let wallList = reactive([])
let wallIndex = ref(0)
let MsgPopup = ref<IPopupType>(null)
let scoringPopup = ref<IPopupType>(null)
let maskFlag = ref(true)
let starCount = ref(5)
let scoringCount = ref(0)
const total = ref(1)
let readImg = ref([])// 优化图片加载
let isScoreFlag = ref(false)// 是否评分
let params = ref({
  classid: wallData.classid,
  pageNum: Math.ceil(wallList.length / 8) + 1,
  pageSize: 9,
  type: '',
})
async function getDetailWall(id: string) {
  let { classList, classListTotal } = JSON.parse(uni.getStorageSync('wall'))
  total.value = classListTotal
  wallList.push(...classList.map((item, index) => {
    if (item._id === id) {
      wallIndex.value = index
      wallData = { ...item, picurl: item.smallPicurl.replace('_small.webp', '.jpg') }
      wallData.userScore && (scoringCount.value = wallData.userScore)
      console.log(index, wallData)
    }
    return { ...item, picurl: item.smallPicurl.replace('_small.webp', '.jpg') }
  }))
}
function maskClick() {
  console.log(maskFlag.value)
  maskFlag.value = !maskFlag.value
}
function maskChange(e) {
  Object.assign(wallData, wallList[e.current])

  wallIndex.value = e.current
  readImg.value.push(wallIndex.value - 1, wallIndex.value, wallIndex.value + 1)
  scoringCount.value = 0
  // 判断是否评分过
  if (wallList[wallIndex.value].userScore) {
    isScoreFlag.value = true
    scoringCount.value = wallList[wallIndex.value].userScore
  }
  if (e.current + 1 !== total.value && e.current === wallList.length - 1) {
    getWallList()
    // 发送请求加入数据
    console.log(e, wallList.length, total.value, '111')
  }
}
async function getWallList() {
  let val
  if (params.value.type) {
    val = await getUserWallListApi(params.value)
  }
  else {
    val = await getWallListApi(params.value)
  }

  if (val) {
    wallList.push(...val.map((item) => {
      wallData = { ...item, picurl: item.smallPicurl.replace('_small.webp', '.jpg') }
      return { ...item, picurl: item.smallPicurl.replace('_small.webp', '.jpg') }
    }))
  }
}

function popOpen() {
  console.log(MsgPopup.value)
  MsgPopup.value.open()
}
function closePopup() {
  MsgPopup.value.close()
}
function goBackHandler() {
  uni.navigateBack({
    fail: () => {
      uni.reLaunch({
        url: '/pages/index/index',
      })
    },
  })
}
function scoringHandler() {
  console.log(wallList[wallIndex.value].userScore, 'wallList[wallIndex.value]')
  isScoreFlag.value = false
  if (wallList[wallIndex.value].userScore) {
    isScoreFlag.value = true
    scoringCount.value = wallList[wallIndex.value].userScore
  }
  scoringPopup.value.open()
}
function closeScoringPopup() {
  // scoringCount.value = wallData.score

  scoringPopup.value.close()
}
async function downloadHandler() {
  // #ifdef H5

  uni.showModal({
    content: '长按保存壁纸',
    showCancel: false,
  })
  // #endif

  // #ifndef H5
  // loading效果

  uni.showLoading({
    title: '下载中...',
    mask: true,
  })
  getDownloadWallApi({ classid: wallData.classid, wallId: wallData._id }).then((res) => {
    if (!res) {
      throw new Error('下载失败')
    }
    uni.getImageInfo({
      src: wallData.picurl,
      success: (success) => {
        uni.saveImageToPhotosAlbum({
          filePath: success.path,
          success: (success) => {
            uni.showToast({
              title: '保存成功',
            })
          },
          fail: (err) => {
            // 取消保存
            if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
              uni.showToast({
                title: '保存失败',
                icon: 'none',
              })
              return
            }
            // 重新授权
            uni.showModal({
              title: '提示',
              content: '需要授权保存相册',

              success: ({ confirm, cancel }) => {
                if (confirm) {
                  uni.openSetting({
                    success: (setting) => {
                      if (setting.authSetting['scope.writePhotosAlbum']) {
                        uni.showToast({
                          title: '获取授权成功',
                        })
                      }
                      else {
                        uni.showToast({
                          title: '获取授权失败',
                        })
                      }
                    },
                  })
                }
              },

            })
          },

        })
      },

    })
  }).catch((err) => {
    console.log(err, 'catch')

    uni.showToast({ title: err.message, icon: 'error' })
  }).finally(() => {

  })

  // #endif
}
async function scoringSubmitHandler() {
  console.log(scoringCount.value, '我的评分')
  await getSetupScoreApi({ classid: wallData.classid, userScore: scoringCount.value.toString(), wallId: wallData._id })
  uni.showToast({ title: '评分成功', icon: 'success' })
  wallList[wallIndex.value] = { ...wallList[wallIndex.value], userScore: scoringCount.value }
  console.log(wallData, wallList[wallIndex.value], 'wallList[wallIndex.value]')

  closeScoringPopup()
}
function classificationHandler() {
  uni.navigateTo({
    url: `/pages/classList/classList?classid=${wallData.classid}&classname=${wallData.classname}`,
  })
}

const heightComputed = computed(() => {
  let height
  // #ifdef MP-WEIXIN
  height = `calc(100vh - ${safeAreaInsets?.bottom}px)`
  // #endif

  // #ifndef MP-WEIXIN
  height = `100vh`
  // #endif

  return height
})

onLoad((options) => {
  if (!options.id) {
    goHome()
    return
  }
  if (options.type === 'share') {
    getDetailWallApi(options.id).then(
      (val) => {
        if (val) {
          wallData = { ...val[0], picurl: val[0].smallPicurl.replace('_small.webp', '.jpg') }
          wallList.push(wallData)
          classificationName.value = options.classificationName
        }
      },

    )
  }
  else {
    params.value.type = options.type
    getDetailWall(options.id)
  }

  // TODO:通过v-if控制图片,加载更丝滑不生效,只能加在内部盒子image中
  readImg.value.push(wallIndex.value - 1, wallIndex.value, wallIndex.value + 1)
})
// #ifndef H5
onShareAppMessage((e) => {
  // 分享给好友
  return {
    title: `花朵壁纸-${wallData.nickname}`,
    path: `/pages/preview/preview?id=${wallData._id}&type=share&classificationName=${classificationName.value}`,
  }
})
// 分享朋友圈
onShareTimeline(() => {
  return {
    title: `花朵壁纸-${wallData.nickname}`,
    imageUrl: '/static/images/flower.png', // 1比1
    query: `id=${wallData._id}&type=share&classificationName=${classificationName.value}`,
  }
})
// #endif
</script>

<template>
  <view class="detailWall relative box-border size-screen" :style="{ height: heightComputed }">
    <!-- <uv-image :src="wallData.smallPicurl" width="100%" height="100vh" @click="maskClick" /> -->

    <uv-swiper
      v-if="wallList.length" :list="wallList" key-name="picurl" :current="wallIndex" height="100vh"
      :autoplay="false" @click="maskClick" @change="maskChange"
    />

    <view v-if="maskFlag" class="info-msg" @click.stop="maskClick">
      <uv-tags
        :text="`${wallIndex + 1} / ${total}`" type="warning" shape="circle" bg-color="#666666"
        border-color="#666666" class="last-mark"
      />
      <view class="py-5px text-46px font-bold">
        {{ getCurrentTime() }}
      </view>
      <view class="text-16px">
        {{ getCurrentDate() }}
      </view>
    </view>

    <!-- 圆角信息盒子 -->
    <view v-if="maskFlag" class="info-box">
      <!-- 信息部分 -->
      <view class="info-item" @click="popOpen">
        <uv-icon name="info-circle" size="24" color="#333" />
        <text class="info-text">信息</text>
      </view>

      <!-- 评分部分 -->
      <view class="info-item" @click="scoringHandler">
        <uv-icon name="star" size="24" color="#ff0000" />
        <text class="info-text">{{ wallData.score }}分</text>
      </view>

      <!-- 下载部分 -->
      <view class="info-item" @click.stop="downloadHandler">
        <uv-icon name="download" size="24" color="#409EFF" />
        <text class="info-text">下载</text>
      </view>
    </view>
    <!-- 返回 -->
    <uv-button
      v-if="maskFlag" shape="circle" color="rgba(42, 37, 36,.5)" class="goBack"
      :style="{ top: `${safeAreaInsets.top === 0 ? 20 : safeAreaInsets.top}px`, height: `${capsuleButtonHeight}px` }"
      @click.stop="goBackHandler"
    >
      <uv-icon name="arrow-left" size="16" color="#fff" />
    </uv-button>
  </view>
  <!-- 信息弹框 -->
  <uni-popup
    ref="MsgPopup" type="bottom" border-radius="10px 10px 0 0" background-color="#fff" animation is-mask-click
    safe-area class="p-10px"
  >
    <uv-row>
      <uv-col span="6" offset="1" text-align="right">
        <view class="title text-18px">
          壁纸信息
        </view>
      </uv-col>
      <uv-col span="1" offset="4" text-align="left">
        <uv-icon class="right-box" name="close" color="#eee" size="24" @click="closePopup" />
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          壁纸id :
        </view>
      </uv-col>
      <uv-col span="10">
        <view>{{ wallData._id }}</view>
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          分类 :
        </view>
      </uv-col>
      <uv-col span="10">
        <view class="color-#7ddd8f underline decoration-green" @click="classificationHandler">
          {{ wallData.classname || classificationName }}
        </view>
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          发布者 :
        </view>
      </uv-col>
      <uv-col span="10">
        <view>{{ wallData.nickname }}</view>
      </uv-col>
    </uv-row>

    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          评分 :
        </view>
      </uv-col>
      <uv-col span="10">
        <view class="flex items-center">
          <uni-rate v-model="wallData.score" :max="5" allow-half disabled />
          <view class="ml-5px">
            {{ wallData.score || '暂无评分' }}
          </view>
        </view>
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          摘要 :
        </view>
      </uv-col>
      <uv-col span="10" class="mr-10px">
        <view class="abstract w-100%">
          <view class="pr-10px">
            {{ wallData.description || '暂无' }}
          </view>
        </view>
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="2" text-align="right">
        <view class="title">
          标签 :
        </view>
      </uv-col>
      <uv-col span="10">
        <view class="flex">
          <uv-tags
            text="标签" plain size="mini" border-color="#21a23a" color="#21a23a" type="success"
            class="mr-4px w-40px"
          />
          <uv-tags
            v-for="(val, index) in wallData.tabs" :key="index" :text="val" plain size="mini" type="success"
            class="mr-4px"
          />
        </view>
      </uv-col>
    </uv-row>
    <uv-row>
      <uv-col span="12">
        <view class="abstract w-100% bg-#eee color-#292424">
          <view class="p-10px">
            声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。
          </view>
        </view>
      </uv-col>
    </uv-row>
  </uni-popup>
  <!-- 评分弹窗 -->
  <uni-popup
    ref="scoringPopup" type="center" background-color="#fff" animation :is-mask-click="false"
    border-radius="10px" class="scoring"
  >
    <uv-row>
      <uv-col span="6" offset="1" text-align="right">
        <view class="title text-18px">
          {{ isScoreFlag ? '已经评分过了~' : '壁纸评分' }}
        </view>
      </uv-col>
      <uv-col span="1.5" offset="3.5" text-align="left">
        <uv-icon class="right-box" name="close" color="#eee" size="24" @click="closeScoringPopup" />
      </uv-col>
    </uv-row>
    <view class="my-20px flex items-center justify-center">
      <uni-rate v-model="scoringCount" :max="5" allow-half :disabled="isScoreFlag" />
      <text class="pl-8px color-#ffcf4a">{{ scoringCount }}分</text>
    </view>
    <view class="flex justify-center">
      <uv-button
        v-if="!isScoreFlag" type="primary" :plain="true" :disabled="!scoringCount" text="确定评分"
        class="w-80px opacity-80" color="#2b2628" @click="scoringSubmitHandler"
      />
    </view>
  </uni-popup>
</template>

<style lang="scss" scoped>
.scoring {
  :deep(.uni-popup__wrapper) {
    width: 80%;
    padding-bottom: 10px;
  }
}

:deep(.uv-tags) {
  opacity: 0.5;
}

.uv-row {
  margin: 10px;

  .uv-col {
    margin: 0 10px;

    .title {
      color: #827d7d;
      font-size: 14px;
    }
  }

  .abstract {
    overflow-wrap: break-word;
  }
}

.header {
  display: flex;
  align-items: center;

  .placeholder {
    flex: 1;
  }

  .center-box {
    flex: none;
  }

  .right-box {
    flex: 1;
    text-align: right;
  }
}

.detailWall {
  .goBack {
    position: absolute;
    left: 20px;
  }

  .info-msg {
    position: absolute;
    top: 20vh;
    left: 10vw;
    right: 10vw;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    color: #fff;
    text-align: center;
  }

  .info-box {
    position: absolute;
    bottom: 10vh;
    left: 10vw;
    right: 10vw;
    display: flex;
    justify-content: space-between;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 40px;
    padding: 10px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    .info-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: 0 20px;
    }
  }
}
</style>
